import history from 'history/browser';
import { ILocalStore } from 'hooks/useLocalStore';
import { action, computed, IReactionDisposer, makeObservable, observable, reaction } from 'mobx';
import RootStore from 'store/RootStore';

import { searchCreate } from 'utils';

type PrivateFields = '_pagesCount' | '_resultsElement' | '_currentPage';

export default class SearchPageStore implements ILocalStore {
    private _pagesCount?: number;
    private _currentPage: number;
    private _resultsElement: HTMLDivElement | null = null;
    private readonly _navigateReaction: IReactionDisposer;

    constructor() {
        makeObservable<SearchPageStore, PrivateFields>(this, {
            _pagesCount: observable,
            _resultsElement: observable,
            _currentPage: observable,
            pagesCount: computed,
            currentPage: computed,
            resultsElement: computed,
            setResultsElement: action.bound,
            setCurrentPage: action.bound,
            setPageCount: action.bound,
        });
        const page =
            RootStore.locationStore.getSearchParams('page') ?? new URLSearchParams(window.location.search).get('page');
        this._currentPage = page ? Number(page) : 1;

        this._navigateReaction = reaction(
            () => String(this._currentPage),
            (page: string) => {
                history.push({
                    pathname: window.location.pathname,
                    search: searchCreate({
                        search: RootStore.locationStore.getSearchParams('search'),
                        types: RootStore.locationStore.getSearchParams('types'),
                        page: page,
                    }),
                });
            },
        );
    }

    get pagesCount(): number | undefined {
        return this._pagesCount;
    }

    get currentPage(): number {
        return this._currentPage;
    }

    get resultsElement(): HTMLDivElement | null {
        return this._resultsElement;
    }

    setResultsElement = (element: HTMLDivElement | null): void => {
        this._resultsElement = element;
    };

    setCurrentPage = (page: number): void => {
        this._currentPage = page;
    };

    setPageCount = (count?: number): void => {
        this._pagesCount = count;
    };

    destroy(): void {
        this._navigateReaction();
    }
}
